#------------------------------------------------------------------------------
# Figure 2. Marginal effects
#==============================================================================

library(rio)
library(data.table)
library(hrbrthemes) # for ggplot
library(ggplot2)
library(tidyr)
library(dplyr)

theme_set(theme_ipsum_rc())

# specify your root directory here
here = '~/Dropbox/project-archive/BG-bk/dataverse'

source(file.path(here,'code','rdata_utils.R'))

# --- load data
mdata = fread(file.path(here,'output','margin_effect_yearly.csv'))

# --- label 
DV_var = unique(mdata[,DV_name])
DV_label = c('Network isolation','Exposure to Dissent')

# -- confidence interval and significance setup for display purposes
mdata[model_year == 0,model_year := 1992-8*2]
mdata[,order := model_year / 8 - 246]

mcoef = paste0('coef',0:1)
mse = paste0('se',0:1)
mlci = paste0('lci',0:1)
muci = paste0('uci',0:1)

mdata = melt(mdata, measure = list(mcoef,mse,mlci,muci), 
	value.name = c("coef", "se","lci","uci"))
setnames(mdata,'variable','election_closeness')
mdata$election_closeness = factor(mdata$election_closeness, labels=c('Non-close Election','Close Election'))

# -- reorder variables
mdata$DV_name = factor(mdata$DV_name,levels=DV_var,labels=DV_label)
mdata$order = factor(mdata$order,levels=c(1,3,4,5,6),labels=c("All","1992","2000","2008","2016") )
mdata = mdata[order!='All',]

fig_compare1 <- mdata  %>% filter(DV_name %in% c('Exposure to Dissent',
	'Network isolation')) %>%
	ggplot(mapping = aes(x=order,y=coef,ymin=lci,ymax=uci,label=sprintf("%.2f",coef),
		color=election_closeness,lty=election_closeness)) + 
	geom_pointrange(stat='identity',position=position_dodge(width=1),size=1.5) + theme_ipsum() + 		
	geom_text(position = position_dodge(width = 1),color='black') +
	scale_color_manual(name="",values=c("gray","red")) + 
	scale_linetype_manual(name="",values=c("dotted","solid"))+
	labs(x=NULL, y="Predicted Margins with 95% Confidence Intervals") + 
	theme(legend.position = "top") +
	facet_wrap(~DV_name,scale='free')

ggsave(file=file.path(here,'output','figure_margins_yearly.png'), plot=fig_compare1, width=7, height=5,dpi=500)
